package cn.iocoder.yudao.module.alipay.service.infoauthaliapp;

import cn.iocoder.yudao.module.alipay.dal.mysql.infothirdaliapp.InfoThirdAliAppMapper;
import cn.iocoder.yudao.module.alipay.util.Tool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenMiniBaseinfoQueryRequest;
import com.alipay.api.response.AlipayOpenMiniBaseinfoQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.alipay.controller.admin.infoauthaliapp.vo.*;
import cn.iocoder.yudao.module.alipay.dal.dataobject.infoauthaliapp.InfoAuthAliAppDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.alipay.convert.infoauthaliapp.InfoAuthAliAppConvert;
import cn.iocoder.yudao.module.alipay.dal.mysql.infoauthaliapp.InfoAuthAliAppMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.alipay.enums.ErrorCodeConstants.*;

/**
 * 授权应用信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class InfoAuthAliAppServiceImpl implements InfoAuthAliAppService {

    @Resource
    private InfoAuthAliAppMapper infoAuthAliAppMapper;

    @Resource
    private InfoThirdAliAppMapper infoThirdAliAppMapper;

    @Override
    public Long createInfoAuthAliApp(InfoAuthAliAppCreateReqVO createReqVO) throws AlipayApiException {
        // 插入
        InfoAuthAliAppDO infoAuthAliApp = InfoAuthAliAppConvert.INSTANCE.convert(createReqVO);
        validateInfoThirdAliAppExistsByAppId(createReqVO.getThirdAppId());
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(String.valueOf(createReqVO.getAppId()));
        if(infoAuthAliAppDO==null){
            infoAuthAliAppDO = new InfoAuthAliAppDO();
        }
        JSONObject appInfo = getAppInfo(createReqVO.getAppAuthToken());
        String alipayOpenMiniBaseinfoQueryResponse = appInfo.getString("alipay_open_mini_baseinfo_query_response");
        JSONObject parse = JSON.parseObject(alipayOpenMiniBaseinfoQueryResponse);
        System.out.println(parse.getString("app_logo"));
        System.out.println(parse.getString("service_phone"));
        infoAuthAliAppDO.setAppLogo(parse.getString("app_logo"));
        infoAuthAliAppDO.setAppName(parse.getString("app_name"));
        infoAuthAliAppDO.setRejectMessage(parse.getString("app_slogan"));
        infoAuthAliAppDO.setOperateStatue("0");
        infoAuthAliAppDO.setAppState("");
        if(infoAuthAliAppDO.getId()!=null){
            infoAuthAliAppDO.setAppAuthCode(createReqVO.getAppAuthCode());
            infoAuthAliAppDO.setAppAuthToken(createReqVO.getAppAuthToken());
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
        }else{
            infoAuthAliAppMapper.insert(infoAuthAliApp);
        }
        log.info("创建授权应用信息：{}", infoAuthAliApp);
        log.info("========================================appId：{}", createReqVO.getAppId());
        log.info("========================================AppAuthToken：{}", createReqVO.getAppAuthToken());
        // 返回
        return infoAuthAliApp.getId();
    }

   public JSONObject getAppInfo(String appAuthToken) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }

        // 构造请求参数以调用接口
        AlipayOpenMiniBaseinfoQueryRequest request = new AlipayOpenMiniBaseinfoQueryRequest();
        request.putOtherTextParam("app_auth_token", appAuthToken);
        // 响应
        AlipayOpenMiniBaseinfoQueryResponse response = alipayClient.certificateExecute(request);
        System.out.println(response);
        System.out.println(JSON.parseObject(response.getBody()));
       return JSON.parseObject(response.getBody());
    }

    private void validateInfoThirdAliAppExistsByAppId(Long thirdAppId) {
        if (infoThirdAliAppMapper.selectByAppId(thirdAppId) == null) {
            throw exception(INFO_THIRD_ALI_APP_NOT_EXISTS);
        }
    }

    @Override
    public void updateInfoAuthAliApp(InfoAuthAliAppUpdateReqVO updateReqVO) throws AlipayApiException {
        // 校验存在
        validateInfoAuthAliAppExists(updateReqVO.getId());
        // 更新
        InfoAuthAliAppDO updateObj = InfoAuthAliAppConvert.INSTANCE.convert(updateReqVO);
        JSONObject appInfo = getAppInfo(updateReqVO.getAppAuthToken());
        String alipayOpenMiniBaseinfoQueryResponse = appInfo.getString("alipay_open_mini_baseinfo_query_response");
        JSONObject parse = JSON.parseObject(alipayOpenMiniBaseinfoQueryResponse);
        updateObj.setAppLogo(parse.getString("app_logo"));
        updateObj.setAppName(parse.getString("app_name"));
        updateObj.setRejectMessage(parse.getString("app_slogan"));
        infoAuthAliAppMapper.updateById(updateObj); 
    }

    @Override
    public void deleteInfoAuthAliApp(Long id) {
        // 校验存在
        validateInfoAuthAliAppExists(id);
        // 删除
        infoAuthAliAppMapper.deleteById(id);
    }

    private void validateInfoAuthAliAppExists(Long id) {
        if (infoAuthAliAppMapper.selectById(id) == null) {
            throw exception(INFO_AUTH_ALI_APP_NOT_EXISTS);
        }
    }

    @Override
    public InfoAuthAliAppDO getInfoAuthAliApp(Long id) {
        return infoAuthAliAppMapper.selectById(id);
    }

    @Override
    public List<InfoAuthAliAppDO> getInfoAuthAliAppList(Collection<Long> ids) {
        return infoAuthAliAppMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<InfoAuthAliAppDO> getInfoAuthAliAppPage(InfoAuthAliAppPageReqVO pageReqVO) {
        return infoAuthAliAppMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InfoAuthAliAppDO> getInfoAuthAliAppList(InfoAuthAliAppExportReqVO exportReqVO) {
        return infoAuthAliAppMapper.selectList(exportReqVO);
    }

    @Override
    public InfoAuthAliAppDO getByAppId(String appId) {
        return infoAuthAliAppMapper.selectByAppId(appId);
    }

}
